/*
 * @Author: YuDianyun
 * @Email: 44208156@qq.com
 * @Date: 2020-06-17 09:00:00
 * @Last Modified by: YuDianyun
 * @Last Modified time: 2020-06-17 16:00:00
 * @Description: 课程发布小作业组件
 */
//import 'dart:html';

import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/pages/common/image.dart';
import 'package:flutter_code_framework/pages/lesson/lesson_publish_event.dart';
import 'package:flutter_code_framework/utils/global.dart';

import 'package:flutter_code_framework/widgets/single_media_picker_widget.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:image_picker/image_picker.dart';

import 'lesson_publish_event.dart';

// ignore: must_be_immutable
class LessonXZYPage extends StatefulWidget {
  String id;
  List<String> urlImages;
  String content;
  LessonXZYPage({this.id, this.urlImages, this.content, Key key})
      : super(key: key);
  @override
  _LessonXYZPageState createState() => _LessonXYZPageState();
}

class _LessonXYZPageState extends State<LessonXZYPage> {
  var evt = new LessonPublishEvent();
  List<File> images = [];
  List<String> datas;
  String contentInfo = "";
  final controller = TextEditingController();
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();

    if (widget.content != null && widget.content != "") {
      setState(() {
        contentInfo = controller.text = widget.content;
      });
    }

    if (widget.urlImages != null && widget.urlImages.length > 0) {
      datas = widget.urlImages;
    } else {
      datas = new List<String>();
    }

    controller.addListener(() {
      //获取输入的值
      contentInfo = controller.text;
      G.eventBus.fire(LessonPublishEvent(
          type: '小作业',
          oldImages: widget.urlImages,
          contentInfo: contentInfo,
          images: images));
    });

    getDataList();
  }

  // ignore: missing_return
  GetScanImagePath getDelImage(String path) {
    if (path.indexOf("http") > -1) {
      widget.urlImages.remove(path);
    } else {
      images.removeWhere((element) => element.path==path);
    }
    G.eventBus.fire(LessonPublishEvent(
        type: '小作业',
        oldImages: widget.urlImages,
        contentInfo: contentInfo,
        images: images));
    setState(() {
      datas.remove(path);
      if (datas!=null&&datas.length<9&&datas[datas.length-1]!="+") {
        datas.add("+");
      }
    });
    Navigator.of(context).pop();
    //Navigator.of(context).pop();
  }

  //取数据
  getDataList() {
    setState(() {
      if (!(datas.length == 9)) {
        datas.add("+");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 24.0, right: 24.0),
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            height: 124,
            child: new TextField(
              decoration: InputDecoration(
                  hintText: "说点什么",
                  hintStyle: TextStyle(
                      color: G.ADColor("#767676", alpha: 0.5), fontSize: 18),
                  border: InputBorder.none,
                  filled: true,
                  fillColor: G.ADColor("#F9F9F9")),
              focusNode: focusNode,
              controller: controller,
              maxLength: 600,
              maxLines: 4,
            ),
          ),
          SizedBox(height: 14.0),
          _gridview(),
          Divider(
            height: 1,
            color: G.ADColor("#979797", alpha: 0.69),
          )
        ],
      ),
    );
  }

  Widget _gridview() {
    return Expanded(
      child: Container(
        height: double.infinity,
        width: double.infinity,
        child: _initGridView(),
      ),
    );
  }

  Widget _initGridView() {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 5,
          mainAxisSpacing: 5,
          childAspectRatio: 1),
      itemCount: datas.length,
      itemBuilder: (BuildContext context, int index) {
        return getItemContainer(datas[index]);
      },
    );
  }

  _initDatas(PickedFile file) {
    if (file!=null&&datas != null && datas.length > 0) {
      if (datas[datas.length - 1] == "+") {
        datas.removeLast();
      }
      datas.add(file.path);
      images.add(File(file.path));

      G.eventBus.fire(LessonPublishEvent(
          type: '小作业',
          oldImages: widget.urlImages,
          contentInfo: contentInfo,
          images: images));
      if (datas.length < 9) {
        datas.add("+");
      }
    }
  }

  Future showBottomSheetDialog(Widget content) {
    return showModalBottomSheet(
        isScrollControlled: true,
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0)),
        ),
        builder: (builder) {
          //可以通过StatefulBuilder 改变sheet状态
          return StatefulBuilder(builder: (context, state) {
            return SingleChildScrollView(
                child: Container(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom),
              child: Padding(
                padding: EdgeInsets.only(top: 20),
                child: content,
              ),
            ));
          });
        });
  }

  //拍照，从相册选照片
  _addPress() {
    print("添加");
    focusNode.unfocus();
    showBottomSheetDialog(Container(
      height: 208.0,
      padding: EdgeInsets.fromLTRB(0, 23, 0, 23),
      color: Colors.transparent,
      child: SingleMediaPickerWidget(
        mediaType: MediaType.image,
        callback: (PickedFile file) {
          Future.delayed(Duration(milliseconds: 200)).then((e) {
            setState(() {
              _initDatas(file);
            });
          });
        },
      ),
    ));
  }

  // ignore: missing_return
  Widget getItemContainer(String item) {
    print(item);
    if (item == "+") {
      return GestureDetector(
        child: Container(
          color: G.ADColor("#DDDDDD", alpha: 0.75),
          alignment: Alignment.center,
          child: Icon(
            SFSymbols.plus,
            size: 24.0,
            color: G.ADColor("#FFFFFF"),
          ),
        ),
        onTap: _addPress,
      );
    } else {
      try {
        if (item.indexOf("http") > -1) {
          return GestureDetector(
            child: CachedNetworkImage(
                imageUrl: item,
                placeholder: (context, url) => Center(child: Text("加载中...")),
                fit: BoxFit.cover),
            onTap: () {
              focusNode.unfocus();
              Navigator.of(context).push(new MaterialPageRoute(
                  builder: (ctx) => new ImageWidget(
                        imageType: ImageType.scan,
                        imageUrl: item,
                        scanCallback: getDelImage,
                      )));
            },
          );
        } else {
          return GestureDetector(
            child: Image.file(File(item), fit: BoxFit.cover),
            onTap: () {
              focusNode.unfocus();
              Navigator.of(context).push(new MaterialPageRoute(
                  builder: (ctx) => new ImageWidget(
                        imageType: ImageType.scan,
                        imageUrl: item,
                        scanCallback: getDelImage,
                      )));
            },
          );
        }
      } catch (e) {}
    }
  }
}
